package mx.com.sinformex.simbel.pages.admin;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tapestry5.Block;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;

import mx.com.sinformex.simbel.db.eos.DataSource;
import mx.com.sinformex.simbel.pages.BasicPage;

/**
 * @author Oscar Ivan Hernandez Ventura [ oscar at sinformex dot com dot mx]
 *
 * @version $ Id : Datasources.java , v 1.0 10/05/2009 angellore $
 */
public class Datasources extends BasicPage {
	
	@Persist
	@Property
	private DataSource ds;
	
	@Inject
	private Block dsDetails;
	
	@Property
	private DataSource detailDs;
	
	private final Log log = LogFactory.getLog(getClass());
	
	public List<DataSource> getDatasources() {
		return getAdminDataAccess().fetchDatasources();
	}
	
	void onActionFromCreate() {
		getSession().setListing(false);
		getSession().setEditing(false);
		getSession().setInserting(true);
		ds = new DataSource();
	}
	
	void onActionFromEdit(String name) {
		getSession().setListing(false);
		getSession().setInserting(false);
		getSession().setEditing(true);
		ds = getAdminDataAccess().getDatasource(name);
	}
	
	void onValidate() {
		Object o = getAdminDataAccess().getDatasource(ds.getName());
		if(o != null) {
			log.error(String.format("The ds %s already exist.", ds.getName()));
			setError(String.format("The ds %s already exist.", ds.getName()));
		}
	}
	
	void onSuccess() {
		if(getError() != null) {
			return;
		}
		if(!getSession().isListing() || ds != null) {
			if(getSession().isEditing()) {
				getAdminDataAccess().updateDatasource(ds);
			} else if(getSession().isInserting()) {
				getAdminDataAccess().saveDatasource(ds);
			}
			ds = null;
			getSession().setListing(true);
			getSession().setEditing(false);
			getSession().setInserting(false);
		}
	}	
	
	Block onActionFromViewDetail(String name) {
		detailDs = getAdminDataAccess().getDatasource(name);
		return dsDetails;
	}

}
